const Router = require('koa-router');
const mysql = require('mysql2/promise');
const bodyParser = require('koa-bodyparser');
const router = new Router();

router.use(bodyParser())
// 定义数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'student',
};

router.get('/product-list', async (ctx) => {
  try {
    // 连接到数据库
    const connection = await mysql.createConnection(dbConfig);

    // 执行查询
    const [rows, fields] = await connection.execute(
      'SELECT list_name, list_img, list_sort, list_price FROM list_product'
    );

    // 关闭数据库连接
    await connection.end();

    // 返回查询结果
    ctx.body = {
      data: rows,
      code: 200,
      message: '查询成功',
    };
  } catch (error) {
    console.error('Failed to query:', error);
    ctx.status = 500;
    ctx.body = { error: '内部服务器错误' };
  }
});

module.exports = router;

